// ========================= ethercatWindows.h =========================
#ifndef ETHERCAT_WINDOWS_H
#define ETHERCAT_WINDOWS_H

#ifdef __cplusplus
extern "C"
{
#endif

#include <stdint.h>
#include "cJSON.h"
#include <stdlib.h>
#include <stdbool.h>

#define MAX_DEVICES 16
#define IO_BITS 16


    // Device kinds on the bus
    typedef enum
    {
        DEV_SERVO_PP = 0,
        DEV_IO = 1,
        DEV_SERVO_CSP = 2,
    } DeviceType;

    // Servo state
    typedef struct
    {
        int32_t position;    // Actual position
        int32_t velocity;    // Actual velocity
        int16_t torque;      // Actual torque (or current)
        int32_t target_position; // Target position (PP)
        uint32_t target_velocity;         // Target velocity (PV)
        uint32_t acc;
        uint32_t dec;
        uint32_t traj_vel; 
        uint16_t status;     // 0x6041
        uint16_t error;      // Fault/err code (vendor-specific)
        uint8_t running;     // 0: idle, 1: executing
        uint16_t stepcnt;   // internal use
    } ServoData;

    // IO state (simple DI/DO bit arrays)
    typedef struct
    {
        uint16_t DO[IO_BITS];
        uint16_t DI[IO_BITS];
    } IOData;

    // Generic device
    typedef struct
    {
        int index; // index by EtherCAT order (0-based for user display)
        char name[32];
        DeviceType type;
        union
        {
            ServoData servo;
            IOData io;
        } u;
    } Device;

    // Public globals (read-only; use helpers to modify)
    extern Device Devices[MAX_DEVICES];
    extern int DeviceCount;
    extern int Port;
    extern char *Ifname;

    // Lifecycle
    int ethercatw_start(); // spawn EtherCAT working thread(s)
    void ethercatw_stop(void);

    // Thread-safe snapshots for TCP publisher
    // Returns number of devices copied into out[] (<= max_out)
    int ethercatw_get_snapshot(Device *out, int max_out);

    // Commands (cheap thread-safe setters that EtherCAT thread will consume)
    int ethercatw_set_do(int slaveIndex /*IO device array index*/, int bit /*1-based*/, int value);
    int ethercatw_move_axis(int slaveIndex /*servo array index*/, int32_t target, int32_t vel, int32_t acc, int32_t dec);
    int ethercatw_stop_axis(int slaveIndex /*servo array index*/);

#ifdef __cplusplus
}
#endif

#endif // ETHERCAT_WINDOWS_H